package com.sun.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Author Sun
 * @Date 2020/4/19 20:22
 * @Version 1.0
 */
public class FileSevlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取下载文件的路径
        String realPath ="E:\\壁纸\\写真\\1.png";
        System.out.println("文件的下载路径是："+realPath);
        //2.截取要下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3.设置响应头头让浏览器支持要下载的东西，文件名为中文的时候需要转码
        resp.setHeader("Content-Disposition", "attachment;filename"+ URLEncoder.encode(fileName, "UTF-8"));
        //4.获取要下载的目标文件的输入流
        FileInputStream in = new FileInputStream(realPath);
        //5.设置字节数组缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //6.获得输出流对象
        ServletOutputStream out = resp.getOutputStream();
        //7.将输入流读取到缓冲区，用输出流将缓冲区的数据输出到客户端
        while ((len = in.read(buffer)) != -1){
            out.write(buffer, 0, len);
        }

        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
